import { defineStore } from "pinia";
import { api } from "@/api";
import router from "@/router";

export const useUserStore = defineStore({
  id: "user",
  state: () => ({
    user: null as any,
    currentOrder: null as any,
    currentOrderItems: [] as any,
  }),
  getters: {
    totalPrice(state) {
      if (!state.currentOrderItems) {
        return 0;
      }
      return state.currentOrderItems.reduce(
        (total: number, item: any) => total + item.Price * item.Number,
        0
      );
    },
  },
  actions: {
    async getUserInfo() {
      if (!localStorage.getItem("token")) return;
      const res = (await api.get("/userinfo")).data;
      this.user = res?.data;
      await this.getCurrentOrder();
    },
    async editUserInfo() {
      if (!this.user) return;
      const res = (await api.patch("/userinfo", this.user)).data;
      await this.getUserInfo();
      return res?.msg;
    },
    loginOut() {
      localStorage.clear();
      this.user = null;
      this.currentOrder = null;
      this.currentOrderItems = null;
      router.push("/");
    },
    async getCurrentOrder() {
      if (!this.user) return;
      const res = (
        await api.get("/order", {
          params: {
            UserID: this.user?.ID,
          },
        })
      ).data;
      this.currentOrder = res?.data;
      await this.getCurrentOrderItems();
    },
    async getCurrentOrderItems() {
      if (!this.currentOrder) return;
      const res = (
        await api.get("/orderitems", {
          params: {
            order: this.currentOrder?.ID,
          },
        })
      ).data;
      this.currentOrderItems = res?.data ?? [];
    },
    async payCurrentOrder() {
      if (!this.currentOrder) return;
      const res = (await api.post("/order", this.currentOrder)).data;
      await this.getUserInfo();
      return res?.msg;
    },
    async finishOrder(id: number) {
      const res = (await api.patch(`/order/${id}`)).data;
      return res?.msg;
    },
  },
});
